package com.edz.zxpmifiapk;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by zhangxianpeng on 2018/4/19.
 */

public class SocketUtil {

    private static SocketUtil socketUtilinstance;
    private static final String TAG = "SocketUtil";
    Socket socket;
    OutputStream os;
    InputStream is;
    String strResData;                      //Server端发送的数据


    public SocketUtil(){
    }

    public static SocketUtil getInstance() {
        if(socketUtilinstance == null){
            synchronized (SocketUtil.class){
                if(socketUtilinstance == null){
                    socketUtilinstance = new SocketUtil();
                }
            }
        }
        return socketUtilinstance;
    }

    /**
     * Client & Server 连接
     */
    public void ConnectServer(){
        try{
            socket = new Socket("192.168.0.34",8989);
            Log.e(TAG,"socket连接是否成功" + socket.isConnected());
        }catch (IOException e){
            Log.e(TAG,"ConnectServer"+e.getMessage());
        }
    }

    /**
     * Client ->  Server
     * @param str_sendData
     */
    public void sendData2Server(String str_sendData){
        ConnectServer();
        if(socket != null ){
            try{
                os = socket.getOutputStream();
                os.write((str_sendData+"\n").getBytes("utf-8"));
                os.flush();
            }catch (IOException e){
                Log.e(TAG,"sendData2Server"+e.getMessage());
            }
        }
    }

    /**
     * Server -> Cient
     * @return
     */
    public String Server2Client(){
        ConnectServer();
        if(socket != null){
            try{
                is = socket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(is);

                byte[] bytes = new byte[10000];
                int length   = dataInputStream.read(bytes);
                strResData   = new String(bytes,0,length,"utf-8");
            }catch (IOException e){
                Log.e(TAG,"getDataFromServer"+e.getMessage());
            }
        }
        return strResData;
    }

    /**
     * 发送心跳机制数据
     * @param strHeartData
     */
    public void sendHeartData(final String strHeartData){
    }

    /**
     * Client & Server 取消连接
     */
    public void disConnectServer(){
        if(socket.isConnected()){
            try {
                os.close();
                is.close();
                socket.close();
                Log.i(TAG,"Util中打印当前socket连接状态"+socket.isConnected());
            }catch (IOException e){
                Log.e(TAG,e.getMessage());
            }
        }
    }
}
